import {esri} from "../../../api/esriAPI";
import * as THREE from 'three'

class ThreeManage {

  isLoad(view) {
    return view.canvas.parentNode.children.length !== 1;
  }

  bind(view, setupCallback) {
    this.setupCallback = setupCallback;
    if (!this.isLoad(view)) {
      this.createThree(view);
      esri.externalRenderers.add(view, this);
    }else{
      this._callbackResult();
    }
  }

  unBind(view) {
    esri.externalRenderers.remove(view, this);
  }

  setup(arcgisContext) {
    this.arcgisContext = arcgisContext;
    this._callbackResult();
  }

  render(arcgisContext) {
    // 更新相机参数
    var cam = arcgisContext.camera;
    if (!this.camera) {
      console.error("three加载失败了");
      return
    }
    this.camera.position.set(cam.eye[0], cam.eye[1], cam.eye[2]);
    this.camera.up.set(cam.up[0], cam.up[1], cam.up[2]);
    this.camera.lookAt(new THREE.Vector3(cam.center[0], cam.center[1], cam.center[2]));
    // console.log("相机位置", this.camera.position)
    // Projection matrix can be copied directly   投影矩阵可以直接复制
    this.camera.projectionMatrix.fromArray(cam.projectionMatrix);
    this.renderer.render(this.scene, this.camera);
  }


  createThree(view) {
    const canvas = document.createElement("canvas");
    canvas.setAttribute("id", "arcgisThree");
    canvas.width = view.width;
    canvas.height = view.height;
    canvas.style.position = "absolute";
    canvas.style.top = "0";
    canvas.style.left = "0";
    view.canvas.parentNode.appendChild(canvas);
    const context = canvas.getContext("webgl");
    const renderer = new THREE.WebGLRenderer({context, premultipliedAlpha: false});
    renderer.setSize(view.width, view.height);
    renderer.setPixelRatio(window.devicePixelRatio);//设置设备像素比。通常用于避免HiDPI设备上绘图模糊
    renderer.setViewport(0, 0, view.width, view.height);//将视口大小设置为(x, y)到 (x + width, y + height).
    // 设置three.js场景
    const scene = new THREE.Scene();
    //设置相机
    const camera = new THREE.PerspectiveCamera();
    this.renderer = renderer;
    this.scene = scene;
    this.camera = camera;
  }

  _callbackResult() {
    if (this.setupCallback) {
      const result = {
        renderer: this.renderer,
        scene: this.scene,
        camera: this.camera,
        arcgisContext: this.arcgisContext
      }
      this.setupCallback(result);
    }
  }

}

export const threeManage = new ThreeManage();
